<template>
  <div>
    <!-- logo部分 -->
  <van-nav-bar fixed>
    <template #left>
       <img src="../../assets/logo.png" class="logo" >
    </template>
    <template #right>
      <van-icon name="search" size="0.48rem" color="#fff" @click="$router.push('/search')"/>
    </template>
  </van-nav-bar>
<!-- 滑动栏部分 -->
  <van-tabs v-model="active" animated sticky offset-top="1.226667rem" >
     <van-tab :title="item.name" v-for="item in channelsList" :key="item.id"><ArticleList  :cId="active"/></van-tab>
  </van-tabs>
<!-- 顶部右侧加号 -->
   <van-icon name="plus" size="0.37333334rem" class="moreChannels" @click="showPopue"/>
<!-- 弹出层组件 -->
   <van-popup v-model="show" class="edit_wrap" >
      <!-- 弹出层的主体区域 -->
      <ChannelEdit @close="show=false" :userChannelsList="channelsList" @sendAddChannel="addChannelFn" @removeChannel="removeChannelFn" ref="ChannelEditRef" @changeChannelEvent="changeChannelEventFN"></ChannelEdit>
    </van-popup>

  </div>
</template>

<script>
// 只有核心代码
import ArticleList from '@/views/Home/ArticleList/index.vue'
import { userChannelAPI, resetChannelAPI } from '@/api'
import ChannelEdit from './ChannelEdit/index.vue'
export default {
  name: 'Home',
  data () {
    return {
      active: 0,
      channelsList: [],
      show: false
    }
  },
  components: { ArticleList, ChannelEdit },
  async created () {
    try {
      const res = await userChannelAPI()
      const { channels } = res.data.data
      this.channelsList = channels
    } catch (error) {
      this.$Notify({ type: 'warning', message: '获取数据失败' })
    }
  },
  methods: {
    // 添加按钮弹出层事件
    showPopue() {
      this.show = true
      this.$refs.ChannelEditRef.isEdit = false
    },
    // 添加事件
    addChannelFn(val) {
      // console.log(val)
      this.channelsList.push(val)
      this.addRemoveEvent()
    },
    // 删除事件
    removeChannelFn(value) {
      this.channelsList.splice(this.channelsList.findIndex(item => item === value), 1)
      this.addRemoveEvent()
    },
    // 封装删除与添加的函数
    async addRemoveEvent() {
      const newArr = this.channelsList.filter(item => item.id !== 0)
      // console.log(newArr)
      // console.log(resetChannelAPI)
      const list = newArr.map((item, index) => {
        const newObj = { ...item }
        newObj.seq = index + 1
        delete newObj.name
        return newObj
      })
      // console.log(list)
      await resetChannelAPI({
        channels: list
      })
    },
    // 弹出层点击后home页面跳转
    changeChannelEventFN(value) {
      console.log(value.id)
      this.active = value.id
    }
  }

}
</script>

<style lang="less" scoped>
.logo{
  width: 100px;
  height: 30px;
}
/* tab内容距离tab导航的距离 */
/deep/ .van-tabs__content{
    padding-top: 44px;
}
// 设置 tabs 容器的样式
/deep/ .van-tabs__wrap {
  padding-right: 30px;
  background-color: #fff;
}

// 设置小图标的样式
.moreChannels {
  position: fixed;
  top: 62px;
  right: 8px;
  z-index: 999;
}
/* 频道编辑弹出层铺满屏幕 */
.edit_wrap{
  width: 100%;
  height: 100%;
}

</style>
